from PyQt5.QtWidgets import QWidget, QMessageBox, QHBoxLayout,QVBoxLayout, QSlider, QPushButton, QLabel, QFileDialog, QApplication, QFrame
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtGui import QIcon, QPixmap, QPalette, QBrush
from PyQt5.QtCore import Qt, QUrl, QTimer
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
import os, time, sys
from uiDef import *

DEFAULT_VIDEO_WIN_DIR = "f:/视频剪辑/Arduino/ws2812/WS2812 RGB灯环炫酷控制.mp4"
DEFAULT_VIDEO_LIPI4A_DIR = "file:///home/sipeed/Desktop/tfcard/media/video/WS2812 RGB灯环炫酷控制.mp4"

class VideoPlayer(QWidget):
    def __init__(self):
        super().__init__()
        self.is_setURL = False
        self.is_pause = True
        
        if sys.platform.startswith('linux'):
            self.file_path = DEFAULT_VIDEO_LIPI4A_DIR
        else:
            self.file_path = DEFAULT_VIDEO_WIN_DIR
        
        #返回主界面
        self.homeBtn = QPushButton(self)
        self.homeBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_home.png)}")
        self.homeBtn.setFixedSize(30, 30)
        self.headerLabel = QLabel(self)
        self.headerLabel.setText("视频播放器")
        self.headerLabel.setStyleSheet("color:white")
        self.hBoxHeader = QHBoxLayout()
        self.hBoxHeader.addStretch(1)
        self.hBoxHeader.addWidget(self.headerLabel)
        self.hBoxHeader.addStretch(1)
        self.hBoxHeader.addWidget(self.homeBtn)

        #进度条
        self.startTimeLabel = QLabel('00:00')
        self.startTimeLabel.setStyleSheet("color:white")
        self.endTimeLabel = QLabel('00:00')
        self.endTimeLabel.setStyleSheet("color:white")
        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setValue(0)
        self.slider.setMinimum(0)
        
        #按钮
        self.playBtn = QPushButton(self)
        self.playBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_play.png)}")
        self.playBtn.setFixedSize(48, 48)
        self.fastBackBtn = QPushButton(self)
        self.fastBackBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_back.png)}")
        self.fastBackBtn.setFixedSize(48, 48)
        self.fastForwardBtn = QPushButton(self)
        self.fastForwardBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_forward.png)}")
        self.fastForwardBtn.setFixedSize(48, 48)
        self.openBtn = QPushButton(self)
        self.openBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_open.png)}")
        self.openBtn.setFixedSize(24, 24)
        
        # 视频显示与播放器
        self.videoOut = QVideoWidget(self) 
        self.videoOut.resize(self.width(), self.height())
        self.videoOut.setStyleSheet("color:white")
        self.player = QMediaPlayer()
        self.player.setVideoOutput(self.videoOut)

        #进度条布局
        self.hBoxSlider = QHBoxLayout()
        self.hBoxSlider.addWidget(self.startTimeLabel)
        self.hBoxSlider.addWidget(self.slider)
        self.hBoxSlider.addWidget(self.endTimeLabel)

        #打开与播放布局
        self.hBoxButton = QHBoxLayout()
        self.hBoxButton.addStretch(1)
        self.hBoxButton.addWidget(self.fastBackBtn)
        self.hBoxButton.addWidget(self.playBtn)
        self.hBoxButton.addWidget(self.fastForwardBtn)
        self.hBoxButton.addStretch(1)
        self.hBoxButton.addWidget(self.openBtn)

        #整体布局
        self.vboxMain = QVBoxLayout()
        self.vboxMain.addLayout(self.hBoxHeader)
        self.vboxMain.addWidget(self.videoOut)
        self.vboxMain.addLayout(self.hBoxSlider)
        self.vboxMain.addLayout(self.hBoxButton)
        self.vboxMain.setStretch(1, 1) #视频控件的比例
        self.setLayout(self.vboxMain)

        #信号与槽
        self.homeBtn.clicked.connect(self.returnHome)
        self.homeBtn.clicked.connect(self.close)
        self.openBtn.clicked.connect(self.openVideoFile)
        self.playBtn.clicked.connect(self.playVideo)
        self.fastBackBtn.clicked.connect(self.fastBack)
        self.fastForwardBtn.clicked.connect(self.fastForward)
        self.player.positionChanged.connect(self.updateProgress)
        self.slider.sliderPressed.connect(self.pauseVideo)
        self.slider.sliderMoved.connect(self.changeProgress)
        self.slider.sliderReleased.connect(self.playVideo)
        
        self.initUI()

    # 初始化界面
    def initUI(self):
        self.resize(WIN_WIDTH, WIN_HEIGHT)
        self.setWindowTitle('简易视频播放器')
        
        self.show()
        
        if self.file_path != "":
            self.file_path = QUrl(self.file_path)
            print(self.file_path)
            try:
                self.player.setMedia(QMediaContent(self.file_path))
                self.is_setURL = True
                self.is_pause = True
                self.playVideo()
                self.pauseVideo()
            except:
                print("defaut file_path err")

    def paintEvent(self, event):
        print("paintEvent")
        palette = QPalette()
        pix = QPixmap("resource/bg/bg_video.png").scaled(self.width(),self.height())
        palette.setBrush(QPalette.Background,QBrush(pix))
        self.setPalette(palette)
        
    # 返回主页
    def returnHome(self):
        print("return home")
        from homeUI import mainWindow
        self.homeWindow = mainWindow()
        self.homeWindow.show()

    # 打开文件夹
    def openVideoFile(self):
        self.file_path,_ = QFileDialog.getOpenFileName(self, "选择文件", "", "*.mp4")
        if self.file_path != "":
            if sys.platform.startswith('linux'):
                self.file_path = QUrl("file://" + self.file_path) #Linux中运行使用这句
            else:
                self.file_path = QUrl(self.file_path) #Windows中运行使用这句
            print(self.file_path)
            self.player.setMedia(QMediaContent(self.file_path))  # 选取视频文件
            self.is_setURL = True
            self.is_pause = True
            self.playVideo()
        
    # 提示
    def Tips(self, message):
        QMessageBox.about(self, "提示", message)

    # 播放/暂停播放
    def playVideo(self):
        if not self.is_setURL:
            self.Tips('请先选择视频文件')
            return
        
        if self.is_pause:
            print("play")
            self.player.play()
            self.is_pause = False
            self.playBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_pause.png)}")
        else:
            print("pause")
            self.player.pause()
            self.is_pause = True
            self.playBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_play.png)}")

    def pauseVideo(self):
        if not self.is_pause:
            self.player.pause()
            self.is_pause = True
            self.playBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_play.png)}")
    
    # 视频快退
    def fastBack(self):
        if not self.is_setURL:
            self.Tips('请先选择视频文件')
            return
        
        num = self.player.position() - int(self.player.duration() / 20)
        self.player.setPosition(num)

    # 视频快进
    def fastForward(self):
        if not self.is_setURL:
            self.Tips('请先选择视频文件')
            return
        
        num = self.player.position() + int(self.player.duration() / 20)
        self.player.setPosition(num)

    # 刷新进度条
    def updateProgress(self, num):
        #print("getPlayTime")
        self.slider.setMaximum(self.player.duration())
        self.slider.setValue(num)
        self.startTimeLabel.setText(time.strftime('%M:%S', time.localtime(self.player.position()/1000)))
        self.endTimeLabel.setText(time.strftime('%M:%S', time.localtime(self.player.duration()/1000)))
    
    # 改变进度
    def changeProgress(self, num):
        self.player.setPosition(num)

    # 确认用户是否要真正退出
    def closeEvent(self, event):
        if __name__ == '__main__':
            reply = QMessageBox.question(self, 'Message',"确定要退出吗？", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                if not self.is_pause:
                    print("stop")
                    self.player.stop()
                event.accept()
            else:
                event.ignore()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = VideoPlayer()
    sys.exit(app.exec_())
